package com.example.demo.controller;

import com.example.demo.commen.R;
import com.example.demo.entity.Notice;
import com.example.demo.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/notice")
@CrossOrigin(origins = "*")
public class NoticeController {

    @Value("${file.upload-dir}")
    private String uploadDir;


    @Autowired
    private NoticeService noticeService;

    // 查询所有城市信息
    @GetMapping
    public List<Notice> getAllNotice() {
        return noticeService.getAllNotice();
    }

    // 根据城市编号查询城市信息
    @GetMapping("/title/{title}")
    public Notice findBytitle(@PathVariable String title) {
        return noticeService.findBytitle(title);
    }

    @PostMapping("/upload-image")
    public R uploadNoticeImage(@RequestParam("image") MultipartFile file,
                               @RequestParam("noticeId") Long noticeId) {

        if (file.isEmpty()) {
            return R.error("请选择要上传的图片");
        }

        try {
            // 创建目标目录
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.exists()) {
                uploadDirFile.mkdirs();
            }

            // 生成文件名 (防止重名)
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + extension;
            String relativePath = "/uploads/" + newFilename;

            // 保存文件
            File destFile = new File(uploadDir + File.separator + newFilename);
            file.transferTo(destFile);

            // 更新数据库中的图片路径
            Notice notice = noticeService.getById(noticeId);
            if (notice != null) {
                notice.setImage(newFilename);
                noticeService.updateById(notice);
            } else {
                return R.error("公告不存在");
            }

            return R.ok().data("imageUrl", newFilename);

        } catch (IOException e) {
            e.printStackTrace();
            return R.error("图片上传失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/image/{id}")
    public R deleteNoticeImage(@PathVariable Long id) {
        Notice notice = noticeService.getById(id);
        if (notice == null) {
            return R.error("公告不存在");
        }

        if (notice.getImage() != null && !notice.getImage().isEmpty()) {
            try {
                // 删除文件
                String filePath = uploadDir + notice.getImage().substring("/uploads/".length());
                File file = new File(filePath);
                if (file.exists()) {
                    if (!file.delete()) {
                        return R.error("文件删除失败");
                    }
                }

                // 更新数据库
                notice.setImage(null);
                noticeService.updateById(notice);

                return R.ok();

            } catch (Exception e) {
                e.printStackTrace();
                return R.error("图片删除失败：" + e.getMessage());
            }
        }

        return R.error("该公告没有上传的图片");
    }
}